<template>
    <div class="app-container">
      <div class="contentBox">
        <div class="searchBox">
          <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="queryParams.name"
                  placeholder="请输入商品名称"
                  clearable
                  @keyup.enter="handleQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-row :gutter="10" style="margin: 16px 0;">
          <el-col :span="1.5">
              <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:goodInfo:add']"
                   @click="toPage('/gasManage/stockManage/good-info/addGood')">
                  <img src="@/assets/images/plus.png" class="normalBtn_icon">
                  <div class="normalBtn_text">新增</div>
              </div>
          </el-col>
          <el-col :span="1.5">
            <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:goodInfo:add']"
                 @click="handleBatchWarehousing">
              <el-icon class="normalBtn_icon2"><Upload /></el-icon>
              <div class="normalBtn_text">导入表格新增商品</div>
            </div>
          </el-col>
          <el-col :span="1.5">
            <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:inventoryHistory:add']"
              @click="handleBatch('batchGoodsInbound')">
              <img src="@/assets/images/inbound_blue.png" class="normalBtn_icon">
              <div class="normalBtn_text">按选中批量入库</div>
            </div>
          </el-col>
          <el-col :span="1.5">
            <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:inventoryHistory:add']"
              @click="handleBatch('batchGoodsOutbound')">
              <img src="@/assets/images/outbound_blue.png" class="normalBtn_icon">
              <div class="normalBtn_text">按选中批量出库</div>
            </div>
          </el-col>
          <el-col :span="1.5">
            <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:stockManage:inventoryCountRecord:add']"
              @click="handleBatch('inventoryCount')">
              <el-icon class="normalBtn_icon2"><Box /></el-icon>
              <div class="normalBtn_text">按选中库存盘点</div>
            </div>
          </el-col>
        </el-row>
        <el-table
          v-loading="loading"
          :data="dataList"
          border
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" :selectable="setSelectable" />
          <el-table-column prop="id" label="商品ID" width="100" :show-overflow-tooltip="true" fixed="left"></el-table-column>
          <el-table-column prop="goodsNo" label="商品编码" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
          <el-table-column prop="name" label="商品名称" width="150" :show-overflow-tooltip="true">
            <template #default="scope">
              <div style="max-width: 120px;color: var(--el-color-primary);cursor: pointer;" class="textOverflow1" @click="toPage('/gasManage/stockManage/good-info/printInOutHistory/'+scope.row.id)">{{ scope.row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="cover" label="商品图片" width="80" align="center">
            <template #default="scope">
              <div class="tableImgBox1">
                <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.cover)"
                  @click="handlePreviewShow(setCoverUrl(scope.row.cover))" v-if="scope.row.cover" />
                <div class="emptyBox" v-else>暂无图标</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="barCode" label="商品条码" width="150" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="warehouseId" label="所属仓库" width="180" :show-overflow-tooltip="true">
            <template #default="scope">
              <div style="width: 154px;" class="textOverflow1">{{ scope.row.warehouseId == 0 ? '暂无' : scope.row.warehouseId}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="shelfId" label="所属货架" width="180" :show-overflow-tooltip="true">
            <template #default="scope">
              <div style="width: 154px;" class="textOverflow1">{{ scope.row.shelfId || '暂无'}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="locationId" label="所属货位" width="180" :show-overflow-tooltip="true">
            <template #default="scope">
              <div style="width: 154px;" class="textOverflow1">{{ scope.row.locationId == 0 ? '暂无' : scope.row.locationId}}</div>
            </template>
          </el-table-column>
          <el-table-column width="200" :show-overflow-tooltip="true">
            <template #header="scope">
              <div class="pageFlex pageAlignCenter">
                <el-text>市场参考价(本年)</el-text>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="历史最高、历史最低将在商品入库之后生成"
                  placement="bottom"
                >
                  <el-icon style="cursor: pointer;"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <template #default="scope">
              <div style="max-width: 180px;font-weight: 500;" class="textOverflow1">当前价格：￥{{scope.row.price}}</div>
              <div style="color: var(--el-color-danger);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最高：￥{{scope.row.maxPrice}}</div>
              <div style="color: var(--el-color-success);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最低：￥{{scope.row.minPrice}}</div>
            </template>
          </el-table-column>
          <el-table-column width="200" :show-overflow-tooltip="true">
            <template #header="scope">
              <div class="pageFlex pageAlignCenter">
                <el-text>采购成本价(本年)</el-text>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="平均成本价、历史最高、历史最低将在商品入库之后生成"
                  placement="bottom"
                >
                  <el-icon style="cursor: pointer;"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <template #default="scope">
              <div style="max-width: 180px;font-weight: 500;" class="textOverflow1">当前成本价：￥{{scope.row.costPrice}}</div>
              <div style="color: var(--el-color-info);max-width: 180px;font-weight: 500;" class="textOverflow1">平均成本价：￥{{scope.row.averageCostPrice || 0}}</div>
              <div style="color: var(--el-color-danger);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最高：￥{{scope.row.maxCostPrice}}</div>
              <div style="color: var(--el-color-success);max-width: 180px;font-weight: 500;" class="textOverflow1">历史最低：￥{{scope.row.minCostPrice}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="150" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="spec" label="规格" width="150"></el-table-column>
          <el-table-column prop="unit" label="单位" width="150"></el-table-column>
          <el-table-column label="操作" width="250" align="center" fixed="right">
              <template #default="scope">
                  <div class="pageFlex pageFlexCenter" style="width: 100%;flex-wrap: wrap;">
                      <el-popconfirm :title="scope.row.isEnable === 1 ? '确认禁用该商品?' : '确认启用该商品?'" confirm-button-text="是" cancel-button-text="否"
                        :width="200" @confirm="handleStatus(scope.row)">
                        <template #reference>
                          <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodInfo:status']">
                            <img src="@/assets/images/edit.png" class="img">
                            <div class="text">{{scope.row.isEnable === 1 ? '禁用' : '启用'}}</div>
                          </div>
                        </template>
                      </el-popconfirm>
                      <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:inventoryHistory:add']"
                          @click="toPage('/gasManage/stockManage/good-info/inbound/'+scope.row.id)" v-if="scope.row.isEnable === 1">
                          <img src="@/assets/images/inbound.png" class="img">
                          <div class="text">入库</div>
                      </div>
                      <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:inventoryHistory:add']"
                           @click="toPage('/gasManage/stockManage/good-info/outbound/'+scope.row.id)" v-if="scope.row.isEnable === 1">
                          <img src="@/assets/images/outbound.png" class="img">
                          <div class="text">出库</div>
                      </div>
                      <div class="pageFlex pageFlexCenter btnSetBox" @click="toPage('/gasManage/stockManage/good-info/goodDetail/'+scope.row.id)">
                          <img src="@/assets/images/fileManage.png" class="img">
                          <div class="text">详情</div>
                      </div>
                      <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodInfo:edit']"
                           @click="toPage('/gasManage/stockManage/good-info/editGood/'+scope.row.id)">
                          <img src="@/assets/images/edit.png" class="img">
                          <div class="text">修改</div>
                      </div>
                      <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:stockManage:goodInfo:delete']"
                          @click="handleDelete(scope.row)">
                          <img src="@/assets/images/delete.png" class="img">
                          <div class="text">删除</div>
                      </div>
                  </div>
              </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据"/>
          </template>
        </el-table>
        <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{total}} 条</div>
            <el-pagination background layout="sizes, prev, pager, next" :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize"
               @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </div>
      <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
      <el-dialog
          :title="uploadModalTitle"
          v-model="uploadModalShow"
          width="400px"
          append-to-body
      >
        <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="uploadHeaders"
            :action="uploadUrl"
            :disabled="uploadIsUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitUploadModal">确 定</el-button>
            <el-button @click="uploadModalShow = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
</template>
<script setup>
import { searchGoodsApi, deleteGoodApi, changeGoodStatus } from '@/api/gasManage/stockManage/goodInfo';
import {ElLoading, ElMessageBox} from 'element-plus';
import { onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const router = useRouter();
const { proxy } = getCurrentInstance();
// ---------------------------------查询----------------------------------------
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const showPreview = ref(false);
const srcList = ref([])
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery(){
    proxy.resetForm("queryRef");
    handleQuery();
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
function handleSizeChange(e){
  if(queryParams.value.pageNum !== 1){
    queryParams.value.pageNum = 1;
  }
  queryParams.value.pageSize = e;
  getList();
}
async function getList(){
  loading.value = true;
  let data = await getGoodsInfoApi(queryParams.value);
  if(data && Array.isArray(data)){
    dataList.value = data;
  }else{
    dataList.value = [];
  }
  loading.value = false;
}
function getGoodsInfoApi(params){
  return new Promise(resolve => {
    searchGoodsApi(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(() => {resolve(false)})
  })
}
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
function toPage(link, row){
  let url = link;
  if(row){
    url += row.id
  }
  router.push(url);
}
// ---------------------------------设置商品状态---------------------------------
const changeLoading = ref(false);
function handleStatus(row){
  if(changeLoading.value) return;
  let params = {
    id: row.id,
    isEnable: row.isEnable === 1 ? 0 : 1,
  }
  changeGoodStatus(params).then(() => {
    changeLoading.value = false;
    proxy.$modal.msgSuccess(row.isEnable === 1 ? '禁用成功' : '启用成功');
    getList();
  }).catch(()=>{
    changeLoading.value = false;
  })
}
// ---------------------------------删除----------------------------------------
function handleDelete(row){
  ElMessageBox.confirm(`确认删除商品名称为【${row.name}】的数据`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow(row);
  }).catch(() => {})
}
async function deleteNow(row){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  deleteGoodApi(row.id).then(()=>{
    loading.close();
    proxy.$modal.msgSuccess(row.name+'商品删除成功');
    getList();
  }).catch(()=>{
    loading.close();
  })
}
// ------------------------------导入表批量添加商品-----------------------------
import { getToken } from "@/utils/auth";
const uploadModalTitle = ref('');
const uploadModalShow = ref(false);
const uploadHeaders = ref({
  Authorization: "Bearer " + getToken()
});
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/stock/goods/importData");
const uploadIsUploading = ref(false);
function handleBatchWarehousing(){
  uploadModalTitle.value = '批量添加商品';
  uploadModalShow.value = true;
}
function handleFileUploadProgress(){
  uploadIsUploading.value = true;
}
function submitUploadModal(){
  proxy.$refs["uploadRef"].submit();
}
function handleFileSuccess(response, file, fileList){
  uploadModalShow.value = false;
  uploadIsUploading.value = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
      "导入结果",
      { dangerouslyUseHTMLString: true }
  );
  getList();
}
function importTemplate(){
  proxy.download("stock/goods/importTemplate", {}, `stock_goods_info_template_${new Date().getTime()}.xlsx`);
}
// --------------------------------选择表格数据---------------------------------
import useToolsData from '@/store/modules/tools';
const toolsDataStore = useToolsData();
const checkedList = ref([]);
function setSelectable(row){
  if(!row.cover){
    return false
  }
  return row.isEnable === 1;
}
function handleSelectionChange(e){
  checkedList.value = e;
}
// --------------------------------批量处理出入库、库存盘点--------------------------------
function handleBatch(name){
  if(name === 'inventoryCount'){
    toolsDataStore.updateIsHandleInventoryCount(true);
    toolsDataStore.updateBatchInventoryCount(checkedList.value);
  }else if(name === 'batchGoodsInbound'){
    toolsDataStore.updateIsHandleInbound(true);
    toolsDataStore.updateBatchGoodsInbound(checkedList.value);
  }else{
    toolsDataStore.updateIsHandleOutbound(true);
    toolsDataStore.updateBatchGoodsOutbound(checkedList.value);
  }
  toPage('/gasManage/stockManage/good-info/'+name);
}
onMounted(()=>{
    getList();
})
</script>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.normalBtn{
  &_icon2{
    margin-right: 10px;
    color: $normalBtnColor;
  }
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: $formBgset4;
  .contentBox{
    width: 100%;
    min-height: $pageMinHeight;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 12px;
    .searchBtn{
        width: 32px;
        height: 32px;
        font-size: 12px;
        padding: 0;
        border: none;
        margin: 0 6px 0 0px;
    }
    .btnSetBox{
        padding: 0 10px;
        box-sizing: border-box;
        border-right: 1px solid $borderColor;
        cursor: pointer;
        margin-bottom: 5px;
        .text{
          height: 16px;
          line-height: 16px;
          color: var(--el-color-primary);
        }
        .img{
          width: 16px;
          height: 16px;
          margin-right: 2px;
        }
        &:nth-child(3n){
          border-right: none;
        }
    }
    .totalText{
        height: 22px;
        font-weight: 400;
        font-size: 14px;
        color: #1D2129;
        line-height: 22px;
    }
  }
}
</style>